package com.myapp.msg.define;

import java.util.HashMap;
import java.util.Map;

import com.myapp.msg.base.BaseMsg;

public class MsgContainer {

	private static MsgContainer msgContainer = null;

	// 消息容器
	private Map<Short, MsgConfigBean> msgsConfig = new HashMap<Short, MsgConfigBean>();

	private Map<Class<? extends BaseMsg>, MsgConfigBean> msgsConfigClass = new HashMap<Class<? extends BaseMsg>, MsgConfigBean>();

	private MsgContainer() {
	}

	public static MsgContainer getInstance() {
		if (msgContainer == null) {
			msgContainer = new MsgContainer();
		}
		return msgContainer;
	}

	/**
	 * 添加消息配置
	 * 
	 * @param msgConfigBean
	 *            消息配置bean
	 */
	public void addMsgConfig(MsgConfigBean msgConfigBean) {
		if (msgsConfig.containsKey(msgConfigBean.getId())) {
			MsgConfigBean sameMsgConfigBean = msgsConfig.get(msgConfigBean
					.getId());
			String info = String.format(
					"Msg[%s] and Msg[%s] have the same Id[%s].",
					sameMsgConfigBean.getLogicalClass().getName()+" "+sameMsgConfigBean.getName(),
					msgConfigBean.getLogicalClass().getName()+" "+msgConfigBean.getName(),
					msgConfigBean.getId());
			throw new IllegalArgumentException(info);
		} else if (msgsConfigClass.containsKey(msgConfigBean.getMsgClass())) {
			String info = String.format("Msg Class[%s] exsit.", msgConfigBean
					.getClass().getName());
			throw new IllegalArgumentException(info);
		} else {
			msgsConfig.put(msgConfigBean.getId(), msgConfigBean);
			msgsConfigClass.put(msgConfigBean.getMsgClass(), msgConfigBean);
		}
	}

	/**
	 * 根据消息id获取配置bean
	 * 
	 * @param id
	 *            消息id
	 * 
	 * @return 消息配置bean
	 */
	public MsgConfigBean getMsgConfigBean(short id) {
		return msgsConfig.get(id);
	}

	/**
	 * 根据消息Class获取配置bean
	 * 
	 * @param id
	 *            消息id
	 * 
	 * @return 消息配置bean
	 */
	public MsgConfigBean getMsgConfigBean(Class<? extends BaseMsg> msg) {
		return msgsConfigClass.get(msg);
	}

	public void clear() {
		msgsConfig.clear();
		msgsConfigClass.clear();
	}
}
